package com.cloud.bc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.NumberUtil;
import com.cloud.bc.model.entity.*;
import com.cloud.bc.mapper.BcPaymenordersMapper;
import com.cloud.bc.model.enums.RechargeEnum;
import com.cloud.bc.model.request.RechargeRequest;
import com.cloud.bc.service.*;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.bc.util.OrderNoUtil;
import com.cloud.common.model.enums.CurrencyTypeEnum;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;

/**
 * 支付订单
 *
 * @author douhaichao code generator
 * @date 2021-01-19 21:19:25
 */
@Service
@AllArgsConstructor
public class BcPaymenordersServiceImpl extends ServiceImpl<BcPaymenordersMapper, BcPaymenorders> implements BcPaymenordersService {
    private final OrderNoUtil orderNoUtil;
    private final BcSetmealsService bcSetmealsService;
    private final BcSetmealOrdersService bcSetmealOrdersService;
    private final BcFinancesService bcFinancesService;
    private final BcFinanceRecordsService bcFinanceRecordsService;

    /**
     * 根据对象属性查找满足条件的第一条数据     *      * @return
     */
    @Override
    public BcPaymenorders selectOne(BcPaymenorders req) {
        QueryWrapper queryWrapper = new QueryWrapper<BcPaymenorders>();
        queryWrapper.setEntity(req);
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 根据条件查询所有
     */
    @Override
    public List<BcPaymenorders> selectAll(BcPaymenorders req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(req);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据对象查询所有分页数据(精确查询)     *      * @return
     */
    @Override
    public IPage<BcPaymenorders> selectPage(Page page, BcPaymenorders req) {
        IPage<BcPaymenorders> list = baseMapper.selectPage(
                page,
                new QueryWrapper<BcPaymenorders>().setEntity(req));
        return list;
    }

    /**
     * 根据对象查询所有分页数据(模糊查询)     *      * @return
     */
    @Override
    public IPage<BcPaymenorders> selectPageByLike(Page page, BcPaymenorders req) {
        QueryWrapper queryWrapper = new QueryWrapper();

        if (null != req.getId()) {
            queryWrapper.eq("id", req.getId());
        }

        if (null != req.getUserId()) {
            queryWrapper.eq("user_id", req.getUserId());
        }

        if (!StrUtil.isEmpty(req.getItem())) {
            queryWrapper.like("item", req.getItem());
        }

        if (null != req.getItemId()) {
            queryWrapper.eq("item_id", req.getItemId());
        }

        if (!StrUtil.isEmpty(req.getItemName())) {
            queryWrapper.like("item_name", req.getItemName());
        }

        if (!StrUtil.isEmpty(req.getItemData())) {
            queryWrapper.like("item_data", req.getItemData());
        }

        if (null != req.getPayAmount()) {
            queryWrapper.eq("pay_amount", req.getPayAmount());
        }

        if (!StrUtil.isEmpty(req.getOrderId())) {
            queryWrapper.like("order_id", req.getOrderId());
        }

        if (!StrUtil.isEmpty(req.getPayWay())) {
            queryWrapper.like("pay_way", req.getPayWay());
        }

        if (!StrUtil.isEmpty(req.getPayOrderId())) {
            queryWrapper.like("pay_order_id", req.getPayOrderId());
        }

        if (!StrUtil.isEmpty(req.getPayData())) {
            queryWrapper.like("pay_data", req.getPayData());
        }

        if (null != req.getPayAt()) {
            queryWrapper.eq("pay_at", req.getPayAt());
        }

        if (!StrUtil.isEmpty(req.getRefundOrderId())) {
            queryWrapper.like("refund_order_id", req.getRefundOrderId());
        }

        if (!StrUtil.isEmpty(req.getRefundData())) {
            queryWrapper.like("refund_data", req.getRefundData());
        }

        if (null != req.getRefundTime()) {
            queryWrapper.eq("refund_time", req.getRefundTime());
        }

        if (!StrUtil.isEmpty(req.getRemark())) {
            queryWrapper.like("remark", req.getRemark());
        }

        if (null != req.getStatus()) {
            queryWrapper.eq("status", req.getStatus());
        }

        if (null != req.getCreateTime()) {
            queryWrapper.eq("create_time", req.getCreateTime());
        }

        if (null != req.getUpdateTime()) {
            queryWrapper.eq("update_time", req.getUpdateTime());
        }
        IPage<BcPaymenorders> list = baseMapper.selectPage(page, queryWrapper);
        return list;
    }

    /**
     * 根据条件统计数据量     *      * @return
     */
    @Override
    public int count(BcPaymenorders req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(req);
        return baseMapper.selectCount(queryWrapper);
    }

    @Override
    public String createRechargeOrder(RechargeRequest req) {
        String orderNo = "";
        BcPaymenorders bcPaymenorders = new BcPaymenorders();
        if (req.getType().equals(RechargeEnum.CANDY.getTitle())) {
            //如果是充值喜糖
            orderNo = orderNoUtil.getCandys();
            bcPaymenorders.setPayAmount(req.getMoney());
            bcPaymenorders.setOrderId(orderNo);
            bcPaymenorders.setPayOrderId(orderNo);
            bcPaymenorders.setUserId(req.getUserId());
            bcPaymenorders.setItem("喜糖充值");
            bcPaymenorders.setItemName("喜糖充值");
            bcPaymenorders.setItemData("喜糖充值:" + req.getMoney());
        } else if (req.getType().equals(RechargeEnum.SETMEAL.getTitle())) {
            //如果是充值套餐
            //查询套餐ID是否存在，如果存在就查询金额
            BcSetmeals bcSetmeals = bcSetmealsService.getById(req.getSetmealId());
            if (null == bcSetmeals) {
                return orderNo;
            }
            orderNo = orderNoUtil.getSetmeals();
            bcPaymenorders.setPayAmount(Convert.toBigDecimal(bcSetmeals.getPrice()));
            bcPaymenorders.setOrderId(orderNo);
            bcPaymenorders.setPayOrderId(orderNo);
            bcPaymenorders.setUserId(req.getUserId());
            bcPaymenorders.setItem("会员套餐");
            bcPaymenorders.setItemId(bcSetmeals.getId());
            bcPaymenorders.setItemName(bcSetmeals.getName());
            bcPaymenorders.setItemData(bcSetmeals.getName() + ":" + bcSetmeals.getPrice());
        }
        baseMapper.insert(bcPaymenorders);
        return orderNo;
    }

    @Transactional
    @Override
    public boolean createNotifyOrder(String orderId, String openOrderId) {
        int updateCount = baseMapper.updatePayStatus(openOrderId, orderId);
        if (updateCount <= 0) {
            //更新失败 退出
            return false;
        }
        BcPaymenorders bcPaymenordersResult = this.selectOne(new BcPaymenorders().setOrderId(orderId));
        if (null == bcPaymenordersResult) {
            return false;
        }
        if (orderId.contains("SE")) {
            //套餐
            Integer itemId = bcPaymenordersResult.getItemId();
            //查询套餐信息，并写入套餐快照表
            BcSetmeals bcSetmeals = bcSetmealsService.selectOne(new BcSetmeals().setId(itemId));
            BcSetmealOrders bcSetmealOrders = new BcSetmealOrders();
            BeanUtil.copyProperties(bcSetmeals, bcSetmealOrders);
            bcSetmealOrders.setPrice(Convert.toInt(bcPaymenordersResult.getPayAmount()));
            bcSetmealOrders.setUserId(bcPaymenordersResult.getUserId());
            bcSetmealOrders.setStatus(1);
            bcSetmealOrders.setSetmealId(itemId);
            bcSetmealOrdersService.save(bcSetmealOrders);
            //写流水
        } else if (orderId.contains("CA")) {
            //查询是否存在当前账户
            BcFinances bcFinances = new BcFinances();
            bcFinances.setUserId(bcPaymenordersResult.getUserId());
            int bcFinancesCount = bcFinancesService.count(bcFinances);
            BigDecimal candyCount = NumberUtil.mul(bcPaymenordersResult.getPayAmount(), 100);
            //用户ID
            bcFinances.setCandyPrice(candyCount);
            if (bcFinancesCount <= 0) {
                bcFinancesService.save(bcFinances);
            } else {
                boolean b = bcFinancesService.add(bcFinances);
            }
            //增加流水
            BcFinanceRecords bcFinanceRecords = new BcFinanceRecords();
            bcFinanceRecords.setUserId(bcPaymenordersResult.getUserId());
            bcFinanceRecords.setCurrencyType(CurrencyTypeEnum.CANDY.getCode());
            bcFinanceRecords.setType(0);
            bcFinanceRecords.setPid(0);
            bcFinanceRecords.setIncome(candyCount);
            bcFinanceRecords.setRemark("充值喜糖:" + candyCount);
            bcFinanceRecordsService.recodeAdd(bcFinanceRecords);
        }
        return true;
    }
}
